package com.eat.what.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@RestController
@RequestMapping("/exec")
public class ExecController {

    @GetMapping("/shell")
    public String getUser() {

        try {
            // 指定要执行的shell脚本路径
            String shellScriptPath = "/root/project/eat-to-java/eatWhat/build.sh";

            // 创建ProcessBuilder对象，指定要执行的命令
            ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", shellScriptPath);

            // 启动进程并等待其执行完毕
            Process process = processBuilder.start();
            int exitCode = process.waitFor();

            // 获取shell脚本的输出结果
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 打印输出结果和退出码
            return  "Shell script output: " + output.toString() + "Exit code: " + exitCode;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return e.getMessage();
        }

    }

}
